package net;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class SessionManager extends IoHandlerAdapter {
	private static SessionManager me;
	private SessionManager() {}
	public static synchronized SessionManager getInstance() {
		if (me == null) {
			me = new SessionManager();
		}
		return me;
	}
	
	private final int BUFFER_SIZE = 10240;
	
	public boolean init(int port) throws IOException {
		IoAcceptor acceptor = new NioSocketAcceptor();

        acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );
        acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));

        acceptor.setHandler( new ClientIoHandlerAdapter() );
        acceptor.getSessionConfig().setReadBufferSize( BUFFER_SIZE );

        // 心跳
        // acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10 );
		acceptor.bind( new InetSocketAddress(port) );
        return true;
	}
}
